package club.pinea.service.impl;

import club.pinea.mapper.RoomMapper;
import club.pinea.model.PoolScore;
import club.pinea.model.Room;
import club.pinea.model.Seat;
import club.pinea.service.SeatService;
import club.pinea.utils.RedisCache;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static club.pinea.constants.RedisPrefix.GAME_POOL_SCORE_PREFIX;
import static club.pinea.constants.RedisPrefix.ROOM_SEAT_PREFIX;

@Service
public class SeatServiceImpl implements SeatService {

    @Autowired
    private RedisCache redisCache;

    @Value("${server.lobby.staySeatTime}")
    public Integer staySeatTime;

    @Value("${server.lobby.maxSeatNum}")
    public Integer maxSeatNum;

    @Value("${server.lobby.maxRoomNum}")
    public Integer maxRoomNum;

    @Resource
    private RoomMapper roomMapper;

    /**
     * 房间倍数
     */
    private int[] multiplyPower = new int[]{2, 5, 20};

    @Override
    public int updateSeatsInfoForStaySeat(String name, int seatId, int room) throws Exception {
        // 根据
        Seat seatModel = redisCache.lIndex(ROOM_SEAT_PREFIX + room, seatId);
        if (StringUtils.isEmpty(seatModel) && seatId < 90) {
            throw new Exception("找不到资源");
        }
        if (seatModel.getSeatStatus() == 1 && seatModel.getSeatUser().equals(name)) {
            seatModel.setSeatStatus(2);
            seatModel.setDate(System.currentTimeMillis() + staySeatTime);
            redisCache.lSet(ROOM_SEAT_PREFIX + room, seatId, seatModel);
            return 1;
        } else {
            throw new IllegalArgumentException("座位信息错误，无法正确留机！");
        }
    }

    /**
     * 初始化room
     */
    @Override
    public void initRoom() {
        List<Room> rooms = roomMapper.queryAll(new Room());
        rooms.forEach(r -> {
            for (int i = 0; i < r.getSeatCount(); i++) {
                Seat seat = new Seat(i);
                seat.setMultiplyPower(r.getMultiplyPower());
                redisCache.rPush(ROOM_SEAT_PREFIX + r.getRoomId(), seat);
            }
        });
    }

    @Override
    public void updateSeat(Seat seat, int seatId, boolean isLeave, int room) {
        if (!isLeave) {//如果是更新座位的请求则查询一遍是否还有其他座位
            if (seat.getSeatUser() != null) {
                checkSeatsByUserName(seat.getSeatUser(), seatId, room);
            }
        }

        redisCache.lSet(ROOM_SEAT_PREFIX + room, seatId, seat);//更新座位
    }


    /**
     * 依赖checkAllSeats 检查座位信息
     *
     * @param seatId
     * @param seatUser
     */
    private void checkSeatsByUserName(String seatUser, int seatId, int room) {
        //更新数据
        List<Seat> list = redisCache.getCacheList(ROOM_SEAT_PREFIX + room);
        for (Seat seat : list) {
            if (Objects.equals(seatUser, seat.getSeatUser())) {
                //判断数据库中有没有当前用户正在坐，如果有则将之前的清除 排除留机可能是需要进入留机的座位
                if (seat.getSeatStatus() == 2 && seat.getSeatId() != seatId) {
                    throw new IllegalArgumentException("您在其他座位还有留机，不能进入这个座位哦！");
                }
                seat.setSeatStatus(0);
                seat.setSeatUser(null);
                redisCache.lSet(ROOM_SEAT_PREFIX + room, seatId, seat);
            }
        }
    }

    @Override
    public Seat getSeatBean(int seatId, int room) {
        return redisCache.lIndex(ROOM_SEAT_PREFIX + room, seatId);
    }

    @Override
    public List<Seat> getRoomSeatDownSeatsByKey(int room) {
        return redisCache.getCacheList(ROOM_SEAT_PREFIX + room, 0, -1);
    }

    @Override
    public int formatSeatByStaySeats(Seat s, int seatId, int room) {
        Seat seat = redisCache.lIndex(ROOM_SEAT_PREFIX + room, seatId);
        if (seat.getSeatStatus() == 2) {
            redisCache.lSet(ROOM_SEAT_PREFIX + room, seatId, s);
            return 1;
        }
        return 0;
    }

    @Override
    public boolean validateUserToken(Integer userId, String token) {
        String vToken = redisCache.getCacheObject(userId.toString());
        return Objects.equals(token, vToken);
    }

    @Override
    public int[] selPoolScores(int seatId, int roomId) {
        PoolScore poolScore = redisCache.lIndex(GAME_POOL_SCORE_PREFIX + roomId, seatId);
        if (poolScore == null) {
            return new int[4];
        }
        return new int[]{poolScore.get_4K(), poolScore.get_SF(), poolScore.get_RS(), poolScore.get_5K()};
    }


}
